<template>
    <div class="report-designer-page">
        <el-card class="designer-card">
            <div class="designer-header">
                <span class="designer-title">{{ isEdit ? '编辑报表' : '新建报表' }}</span>
            </div>
            <el-form :model="form" label-width="78px" class="designer-form" :inline="true">
                <el-form-item label="报表名称" prop="name" required>
                    <el-input v-model="form.name" style="width:220px" />
                </el-form-item>
                <el-form-item label="分组">
                    <el-select v-model="form.group" placeholder="请选择分组" style="width:120px">
                        <el-option v-for="g in groupOptions" :key="g" :label="g" :value="g" />
                    </el-select>
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="form.desc" style="width:280px" />
                </el-form-item>
                <el-form-item label="图表类型">
                    <el-radio-group v-model="form.chartType" size="small">
                        <el-radio-button label="table">表格</el-radio-button>
                        <el-radio-button label="bar">柱状图</el-radio-button>
                        <el-radio-button label="line">折线图</el-radio-button>
                        <el-radio-button label="pie">饼图</el-radio-button>
                        <el-radio-button label="funnel">漏斗图</el-radio-button>
                    </el-radio-group>
                </el-form-item>
            </el-form>

            <div class="designer-main">
                <!-- 字段选择区 -->
                <el-card class="fields-card" shadow="never">
                    <div class="fields-title">可用字段</div>
                    <el-tag v-for="field in allFields" :key="field" class="field-tag" @click="addField(field)"
                        :type="form.fields.includes(field) ? 'info' : 'default'"
                        style="margin-right:6px; margin-bottom:7px; cursor:pointer;">
                        {{ field }}
                    </el-tag>
                </el-card>

                <!-- 拖拽/选中字段 -->
                <el-card class="fields-selected-card" shadow="never">
                    <div class="fields-title">已选字段</div>
                    <draggable v-model="form.fields" item-key="name" direction="horizontal">
                        <template #item="{ element, index }">
                            <el-tag closable @close="removeField(element)" type="success"
                                style="margin-right:6px; margin-bottom:7px; font-weight:bold; cursor:move;">
                                {{ element }}
                            </el-tag>
                        </template>
                    </draggable>
                    <div v-if="!form.fields.length" style="color:#999; margin-top:8px;">请点击上方字段以添加</div>
                </el-card>

                <!-- 分组与聚合配置 -->
                <el-card class="groupby-card" shadow="never">
                    <div class="fields-title">分组/聚合配置</div>
                    <el-form label-width="58px" size="small">
                        <el-form-item label="分组字段">
                            <el-select v-model="form.groupby" placeholder="选择分组字段" style="width:120px">
                                <el-option v-for="f in form.fields" :key="f" :label="f" :value="f" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="聚合方式">
                            <el-select v-model="form.agg" placeholder="选择聚合方式" style="width:120px">
                                <el-option v-for="agg in aggOptions" :key="agg" :label="agg" :value="agg" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                </el-card>

                <!-- 实时预览区 -->
                <el-card class="preview-card" shadow="never">
                    <div class="fields-title">报表实时预览</div>
                    <div v-if="form.chartType === 'table'">
                        <el-table :data="previewData" border height="220">
                            <el-table-column v-for="f in form.fields" :key="f" :prop="f" :label="f" />
                        </el-table>
                    </div>
                    <div v-else>
                        <v-chart :option="getEchartsOption(form, previewData)" autoresize style="height:230px;" />
                    </div>
                </el-card>
            </div>
            <div style="text-align:right;margin-top:18px;">
                <el-button size="small" @click="goBack">返回</el-button>
                <el-button type="primary" @click="saveReport">保存报表</el-button>
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import VChart from 'vue-echarts'
import draggable from 'vuedraggable'
import { ElMessage } from 'element-plus'

// 模拟全部字段（可来自数据集）
const allFields = [
    '日期', '产品', '地区', '客户', '销售额', '数量', '成本', '利润', '负责人', '渠道'
]
const groupOptions = ['销售', '市场', '生产', '人力', '财务']
const aggOptions = ['合计', '平均', '最大值', '最小值', '计数']

// 路由相关
const route = useRoute()
const router = useRouter()

// 新建/编辑模式
const isEdit = computed(() => !!route.params.id)

// 报表表单
const form = reactive({
    name: '',
    group: '',
    desc: '',
    chartType: 'table',
    fields: [],
    groupby: '',
    agg: ''
})

// 预览数据
const previewData = ref([])

// 初始化（模拟读取已有报表）
onMounted(() => {
    if (isEdit.value) {
        // 从 localStorage 里找到那条报表
        const all = JSON.parse(localStorage.getItem('reports') || '[]')
        const current = all.find(r => r.id === Number(route.params.id))
        if (current) {
            // 把全部字段赋值给 form
            Object.assign(form, {
                name: current.name,
                group: current.group,
                desc: current.desc,
                chartType: current.chartType,
                fields: [...current.fields],
                groupby: current.groupby,
                agg: current.agg
            })
            previewData.value = current.data || []
        }
    }
    // 对于新建报表，调用 genPreviewData() 即可
    if (!isEdit.value) {
        genPreviewData()
    }
})


// 字段添加/删除
function addField(field) {
    if (!form.fields.includes(field)) {
        form.fields.push(field)
        genPreviewData()
    }
}
function removeField(field) {
    form.fields = form.fields.filter(f => f !== field)
    genPreviewData()
}

// 预览数据自动生成
function genPreviewData() {
    // 根据选中字段模拟出10条数据
    previewData.value = Array.from({ length: 10 }, (_, i) => {
        const row = {}
        for (let f of form.fields) {
            if (f === '日期') row[f] = `2024-07-${String(i + 1).padStart(2, '0')}`
            else if (f === '销售额' || f === '数量' || f === '成本' || f === '利润')
                row[f] = Math.floor(Math.random() * 10000) + 1000
            else if (f === '地区') row[f] = ['华北', '华南', '华东'][i % 3]
            else if (f === '产品') row[f] = ['A产品', 'B产品', 'C产品'][i % 3]
            else if (f === '客户') row[f] = '客户' + (i + 1)
            else if (f === '负责人') row[f] = '张三'
            else if (f === '渠道') row[f] = ['直营', '经销', '分销'][i % 3]
            else row[f] = '-'
        }
        return row
    })
}

// 监听字段变化实时生成数据
watch(() => [...form.fields], genPreviewData, { deep: true })

// 动态生成ECharts配置
function getEchartsOption(form, data) {
    if (!data || !form.fields.length) return {}
    // 取“日期/产品/地区”为x轴，其他为y轴
    let xField = form.fields.find(f => ['日期', '产品', '地区', '客户', '负责人', '渠道'].includes(f)) || form.fields[0]
    let yField = form.fields.find(f => ['销售额', '数量', '成本', '利润'].includes(f)) || form.fields[1]
    const xData = data.map(d => d[xField])
    const yData = data.map(d => d[yField])
    if (form.chartType === 'bar') {
        return {
            tooltip: { trigger: 'axis' },
            xAxis: { type: 'category', data: xData },
            yAxis: { type: 'value' },
            series: [{ type: 'bar', data: yData, name: yField, itemStyle: { borderRadius: 4 } }]
        }
    } else if (form.chartType === 'line') {
        return {
            tooltip: { trigger: 'axis' },
            xAxis: { type: 'category', data: xData },
            yAxis: { type: 'value' },
            series: [{ type: 'line', data: yData, name: yField, smooth: true }]
        }
    } else if (form.chartType === 'pie') {
        return {
            tooltip: { trigger: 'item' },
            series: [{
                type: 'pie',
                radius: ['40%', '80%'],
                data: data.map(d => ({ value: d[yField], name: d[xField] }))
            }]
        }
    } else if (form.chartType === 'funnel') {
        return {
            tooltip: { trigger: 'item' },
            series: [{
                type: 'funnel',
                left: '10%',
                width: '80%',
                minSize: '40%',
                label: { show: true, position: 'inside' },
                data: data.map(d => ({ value: d[yField], name: d[xField] }))
            }]
        }
    }
    return {}
}

// 保存报表（可写入本地/后端/全局状态）
function saveReport() {
    if (!form.name) return ElMessage.warning('请填写报表名称')
    if (!form.fields.length) return ElMessage.warning('请选择字段')

    let all = JSON.parse(localStorage.getItem('reports') || '[]')
    if (isEdit.value) {
        // 找到原报表
        const old = all.find(r => r.id === Number(route.params.id))
        all = all.map(r =>
            r.id === Number(route.params.id)
                ? {
                    ...form,
                    id: Number(route.params.id),
                    // 保留原来的 created 字段
                    created: old?.created || new Date().toISOString().slice(0, 10),
                    fields: [...form.fields],
                    data: [...previewData.value] // 用预览的数据
                }
                : r
        )
    } else {
        // 新建
        all.unshift({
            ...form,
            id: Date.now(),
            created: new Date().toISOString().slice(0, 10),
            fields: [...form.fields],
            data: [...previewData.value]
        })
    }

    localStorage.setItem('reports', JSON.stringify(all))
    ElMessage.success('报表已保存！')
    goBack()
}

// 自动生成数据
function genReportData(fields) {
  const rows = []
  // 先找出可作为x轴的字段
  const xField = fields.find(f => ['日期', '类别', '产品', '地区', '客户', '负责人', '渠道'].includes(f))
  // 先找出可作为y轴的字段
  const yField = fields.find(f => ['数值', '销售额', '数量', '成本', '利润'].includes(f))
  // 没有关键字段，直接返回空
  if (!xField || !yField) return []
  for (let i = 0; i < 7; i++) {
    const row = {}
    for (const f of fields) {
      if (f === xField) {
        // x轴字段
        if (f === '日期') row[f] = `2024-07-${String(i + 1).padStart(2, '0')}`
        else if (f === '类别') row[f] = ['A', 'B', 'C', 'D'][i % 4]
        else if (f === '产品') row[f] = ['A产品', 'B产品', 'C产品'][i % 3]
        else if (f === '地区') row[f] = ['华北', '华南', '华东'][i % 3]
        else if (f === '客户') row[f] = '客户' + (i + 1)
        else if (f === '负责人') row[f] = '张三'
        else if (f === '渠道') row[f] = ['直营', '经销', '分销'][i % 3]
        else row[f] = f + (i + 1)
      } else if (f === yField) {
        // y轴字段
        row[f] = Math.floor(Math.random() * 5000) + 500
      } else {
        // 其它字段
        row[f] = '-'
      }
    }
    rows.push(row)
  }
  return rows
}



function goBack() {
    router.back()
}
</script>

<script>
import { watch } from 'vue'
export default { name: 'ReportDesigner' }
</script>

<style scoped>
.report-designer-page {
    padding: 24px;
    background: #f7f8fa;
}

.designer-card {
    max-width: 1240px;
    margin: 0 auto;
    border-radius: 12px;
}

.designer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.designer-title {
    font-size: 20px;
    font-weight: 600;
}

.designer-form {
    margin-bottom: 10px;
}

.designer-main {
    display: flex;
    gap: 16px;
    margin-top: 16px;
    margin-bottom: 16px;
}

.fields-card,
.fields-selected-card,
.groupby-card,
.preview-card {
    flex: 1;
    min-width: 180px;
    min-height: 180px;
    padding-bottom: 12px;
    border-radius: 8px;
}

.fields-title {
    font-weight: bold;
    color: #555;
    margin-bottom: 10px;
    font-size: 15px;
}

.field-tag {
    user-select: none;
}
</style>
